<template>
  <div>
    <van-form @submit="onSubmit">
      <van-field
        ref='username'
        v-model="username"
        name="用户名"
        label="用户名"
        placeholder="用户名"
        :rules="[{ required:true, message: '有三个数字...' }]"
      />
      <van-field
        v-model="password"
        type="password"
        name="密码"
        label="密码"
        placeholder="密码"
        :rules="[{ required: true, message: '请填写密码' }]"
      />
      <div style="margin: 16px;">
        <van-button round block type="info" native-type="submit">提交</van-button>
      </div>
    </van-form>
  </div>
</template>

<script>
import { instance2 } from '@/utils/http'
import Vue from 'vue'
import { Form, Field, Button, Dialog, Toast } from 'vant'
import { mapMutations } from 'vuex'
Vue.use(Form)
Vue.use(Field)
Vue.use(Button)
export default {
  data() {
    return {
      username: '',
      password: ''
    }
  },
  methods: {
    ...mapMutations('tabbar', ['hide', 'show']),
    validator(val) {
      return /^1\d{3,}$/.test(val)
    },
    // 异步校验函数返回 Promise
    asyncValidator(val) {
      return new Promise((resolve) => {
        Toast.loading('验证中...')
        setTimeout(() => {
          Toast.clear()
          resolve(/\d{3}/.test(val))
        }, 500)
      })
    },
    onSubmit() {
      instance2.post('/api/user/signin', {
        username: this.username,
        password: this.password
      }).then(res => {
        console.log('3.login的res---->', res)
        localStorage.setItem('token', res.token)
        this.$router.push(this.$route.query.redirect)
      }).catch(() => {
        // alert('用户名或者密码输入错误...')
        Dialog.alert({
          title: '注意了！',
          message: '用户名或者密码输入错误...',
          theme: 'round-button'
        }).then(() => {
          this.username = ''
          this.password = ''
          this.$refs.username.focus() // ref链找到username这个组件，调用filed的focus方法
        })
      })
    }
  },
  created() {
    this.hide()
  },
  beforeDestroy() {
    this.show()
  }
}
</script>

<style>

</style>
